#include <iostream>

struct Node {
    int val;
    Node *prev;
    Node *next;
};

Node *circle_delete(Node head[], int m)
{
    Node *p = head;

    if (p == NULL) {
        return NULL;
    }

    while (p->next != p) {
        for (int i = 0; i < m - 1; ++i) {
            p = p->next;
        }

        p->prev->next = p->next;
        p->next->prev = p->prev;
        p = p->next;
    }

    return p;
}

void link(Node *nodes, int i, int prev, int next)
{
    if (prev != -1) {
        nodes[i].prev = &nodes[prev];
    }

    if (next != -1) {
        nodes[i].next = &nodes[next];
    }
}

int main(int argc, const char *argv[])
{

    Node nodes[14] = {
        {0, NULL, NULL},
        {1, NULL, NULL},
        {2, NULL, NULL},
        {3, NULL, NULL},
        {4, NULL, NULL},
        {5, NULL, NULL},
        {6, NULL, NULL},
        {7, NULL, NULL},
        {8, NULL, NULL},
        {9, NULL, NULL},
        {10, NULL, NULL},
        {11, NULL, NULL},
        {12, NULL, NULL},
        {13, NULL, NULL}
    };
    link(nodes, 0, 13, 1);
    link(nodes, 1, 0, 2);
    link(nodes, 2, 1, 3);
    link(nodes, 3, 2, 4);
    link(nodes, 4, 3, 5);
    link(nodes, 5, 4, 6);
    link(nodes, 6, 5, 7);
    link(nodes, 7, 6, 8);
    link(nodes, 8, 7, 9);
    link(nodes, 9, 8, 10);
    link(nodes, 10, 9, 11);
    link(nodes, 11, 10, 12);
    link(nodes, 12, 11, 13);
    link(nodes, 13, 12, 0);

    std::cout << circle_delete(nodes, 4)->val << std::endl;
    return 0;
}
